package com.zc.wxPay.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thoughtworks.xstream.XStream;
import com.zc.custom.domain.ChargeCustomOrderInfo;
import com.zc.custom.domain.ChargeCustomUser;
import com.zc.custom.mapper.ChargeCustomOrderInfoMapper;
import com.zc.custom.mapper.ChargeCustomUserMapper;
import com.zc.iotDevice.domain.IotDeviceSubsidiaryPort;
import com.zc.operator.domain.ChargeStation;
import com.zc.operator.mapper.ChargeStationMapper;
import com.zc.wxPay.domain.WxPay;
import com.zc.wxPay.entity.OrderQueryInfo;
import com.zc.wxPay.entity.QueryReturnInfo;
import com.zc.wxPay.service.WXPayService;
import com.zc.wxPay.util.Configure;
import com.zc.wxPay.util.HttpRequest;
import com.zc.wxPay.util.RandomStringGenerator;
import com.zc.wxPay.util.Signature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:gaojikun
 * @Date:2023-06-14 10:02
 * @Description: 微信支付定时任务
 */
@Component
public class WXPayTaskController {

    @Autowired
    private WXPayService wXPayService;

    @Autowired
    private ChargeCustomOrderInfoMapper chargeCustomOrderInfoMapper;

    @Autowired
    private ChargeStationMapper chargeStationMapper;

    @Autowired
    private ChargeCustomUserMapper chargeCustomUserMapper;

    /**
     * @Author:gaojikun
     * @Description:定时查询待支付订单和已申请退款订单（发送订单查询） 未付款的待支付订单直接关闭。
     * 已付款的待支付订单修改订单状态 + 业务逻辑处理。
     * 已退款的已申请退款订单修改订单状态 + 业务逻辑处理。
     */
    @Scheduled(cron = "0 */10 * * * ?")
    @Transactional
    public void updateWXPayInfoByOrderInfo() throws Exception {
        System.out.println("*************定时任务查询订单开始*************");

        List<String> stateList = new ArrayList<String>() {{
            add("0");
            add("4");
        }};
        WXPayDealMethoid(stateList);

        System.out.println("*************定时任务查询订单结束*************");
    }


//    @Scheduled(cron = "0 0 23 * * ?")
//    @Transactional
//    public void updateAllWXPayInfoByOrderInfo() throws Exception {
//        System.out.println("*************定时任务查询订单开始*************");
//
//        List<String> stateList = new ArrayList<String>(){{add("0");add("4");}};
//        WXPayDealMethoid(stateList);
//
//        System.out.println("*************定时任务查询订单结束*************");
//    }

    public void WXPayDealMethoid(List<String> stateList) throws Exception {
        WxPay wxPay = new WxPay();

        //查询搜有订单
        List<ChargeCustomOrderInfo> chargeCustomOrderInfos = chargeCustomOrderInfoMapper.selectChargeCustomOrderInfoAllList(null);
        for (ChargeCustomOrderInfo orderInfo : chargeCustomOrderInfos) {
            //查询场站信息
            ChargeStation chargeStation = chargeStationMapper.selectChargeStationByChargeStationCode(orderInfo.getChargeStationCode());
            if (stateList.contains(orderInfo.getOrderInfoStatus())) {

                OrderQueryInfo order = new OrderQueryInfo();
                order.setAppid(Configure.getAppID());
                order.setMch_id(chargeStation.getMchId());
                order.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
                order.setOut_trade_no(orderInfo.getOrderInfoCode());
                //生成签名
                String sign = Signature.getSign(order, chargeStation.getMchKey());
                order.setSign(sign);

                String result = HttpRequest.sendPost(Configure.getQuery_url(), order);
//                System.out.println(result);
                XStream xStream = new XStream();
                xStream.alias("xml", QueryReturnInfo.class);
                xStream.ignoreUnknownElements();
                Class<?>[] classes = new Class[]{QueryReturnInfo.class};
                xStream.allowTypes(classes);
                Object preOrderResult = xStream.fromXML(result);
                ObjectMapper objectMapper = new ObjectMapper();
                QueryReturnInfo returnInfo = objectMapper.convertValue(preOrderResult, QueryReturnInfo.class);
                if ("SUCCESS".equals(returnInfo.getReturn_code()) && returnInfo.getReturn_code().equals(returnInfo.getResult_code())) {
                    if ("SUCCESS".equals(returnInfo.getTrade_state())) {
                        //SUCCESS--支付成功
                        BigDecimal cash_fee = new BigDecimal(String.valueOf(returnInfo.getCash_fee())).divide(new BigDecimal("100"));
//                        //账户余额变动
//                        ChargeCustomUser chargeCustomUser = chargeCustomUserMapper.selectChargeCustomUserByOpenid(orderInfo.getCustomCode());
//                        chargeCustomUser.setAvailableBalance(chargeCustomUser.getAvailableBalance().add(cash_fee));
//                        int i = chargeCustomUserMapper.updateChargeCustomUser(chargeCustomUser);
//                        if (i != 1) {
//                            System.out.println("=============定时任务查询订单（支付成功）出现问题，用户账户余额变动失败=============");
//                            continue;
//                        }
                        //修改订单状态为已支付
                        orderInfo.setOrderInfoStatus("1");
                        orderInfo.setPaymentAmount(cash_fee);
                        orderInfo.setTransactionId(returnInfo.getTransaction_id());
                        int i = chargeCustomOrderInfoMapper.updateChargeCustomOrderInfo(orderInfo);
                        if (i != 1) {
                            System.out.println("=============定时任务查询订单（支付成功）出现问题，修改订单状态为已支付失败=============");
                            continue;
                        }
                        continue;
                    } else if ("NOTPAY".equals(returnInfo.getTrade_state())) {
                        //NOTPAY--未支付
                        ChargeCustomOrderInfo disOrderInfo = chargeCustomOrderInfoMapper.selectChargeCustomOrderInfoByOrderInfoCode(orderInfo.getOrderInfoCode());
                        disOrderInfo.setOrderInfoStatus("2");
                        disOrderInfo.setOrderStatus("3");
                        disOrderInfo.setPaymentAmount(new BigDecimal("0"));
                        int i = chargeCustomOrderInfoMapper.updateChargeCustomOrderInfo(disOrderInfo);
                        if (i != 1) {
                            System.out.println("=============定时任务查询订单（取消支付）出现问题，修改订单状态为取消支付失败=============");
                        }
                        continue;
                    } else if ("CLOSED".equals(returnInfo.getTrade_state())) {
                        //CLOSED--已关闭
                        wxPay.setOutTradeNo(orderInfo.getOrderInfoCode());
                        wxPay = wXPayService.closeOrder(wxPay);
                        if (wxPay.getStatus() == 500) {
                            System.out.println("=============定时任务查询订单（关闭订单）出现问题，修改订单状态为已关闭失败=============");
                        }
                        continue;
                    } else if ("REFUND".equals(returnInfo.getTrade_state())) {
                        //REFUND--转入退款
                        wxPay.setOutTradeNo(orderInfo.getOrderInfoCode());
                        wXPayService.refundQuery(wxPay);
                        if (wxPay.getStatus() == 500) {
                            System.out.println("=============定时任务查询订单（查询退款）出现问题，查询退款失败=============");
                        }
                        continue;
                    } else if ("USERPAYING".equals(returnInfo.getTrade_state()) || "ACCEPT".equals(returnInfo.getTrade_state())) {
                        //USERPAYING--用户支付中 //ACCEPT--已接收，等待扣款
                        continue;
                    } else if ("PAYERROR".equals(returnInfo.getTrade_state())) {
                        //PAYERROR--支付失败(其他原因，如银行返回失败)
                        ChargeCustomOrderInfo disOrderInfo = chargeCustomOrderInfoMapper.selectChargeCustomOrderInfoByOrderInfoCode(orderInfo.getOrderInfoCode());
                        disOrderInfo.setOrderInfoStatus("6");
                        disOrderInfo.setOrderStatus("4");
                        disOrderInfo.setPaymentAmount(new BigDecimal("0"));
                        int i = chargeCustomOrderInfoMapper.updateChargeCustomOrderInfo(disOrderInfo);
                        if (i != 1) {
                            System.out.println("=============定时任务查询订单（支付失败）出现问题，修改订单状态为支付失败失败=============");
                        }
                        continue;
                    } else if ("REVOKED".equals(returnInfo.getTrade_state())) {
                        //REVOKED--已撤销(刷卡支付)
                        ChargeCustomOrderInfo disOrderInfo = chargeCustomOrderInfoMapper.selectChargeCustomOrderInfoByOrderInfoCode(orderInfo.getOrderInfoCode());
                        disOrderInfo.setOrderInfoStatus("7");
                        disOrderInfo.setPaymentAmount(new BigDecimal("0"));
                        int i = chargeCustomOrderInfoMapper.updateChargeCustomOrderInfo(disOrderInfo);
                        if (i != 1) {
                            System.out.println("=============定时任务查询订单（已撤销）出现问题，修改订单状态为已撤销失败=============");
                        }
                        continue;
                    }
                }
            }
        }


    }


}
